package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //类似正则表达式匹配路径类
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        //将父接口servletRequest转换为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String ip = request.getRemoteAddr();
        System.out.println("访客：" + ip);
        //1.获取当前拦截到的路径地址 reqeustURI  ("/backend/index.html")
        String requestURI = request.getRequestURI();

        //2.定义放行的资源路径数组
        String[] urls = {
                "/backend/**", "/front/**", "/employee/login", "/user/sendMsg", "/user/login"};
        //注意：路径中的2个*，antPathMatcher会解析匹配作为代表任意的字符

        //3.判断本次请求的路径是否需要处理
        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                //放行
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        //4.判断商家端登录状态
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if (employee != null) {
            //登录了，放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //5.判断用户端登录状态
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            //登录了，放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //没有登录
        //return R.error("NOTLOGIN"); 这里是过滤器，没有返回值自动转换为json，需要手动
        R<Object> r = R.error("NOTLOGIN");
        //转换为json
        String jsonStr = JSON.toJSONString(r);
        //手动设置响应数据类型
        servletResponse.setContentType("application/json;charset=utf-8");
        servletResponse.getWriter().print(jsonStr);
    }


    @Override
    public void destroy() {

    }
}
